/**
 * @description 邀友领取
 */
import style from './styles/GetCoupon.less';
import classnames from "classnames";
import React, { Component } from 'react';
import { Toast } from 'wd-mobile';
import util from "commons/util";
import TimmerBtn from "components/TimmerBtn";

//api
import { receive_red_packet } from 'api_xukaiyu/app/share_redpacket';
import { loginStatus, logout } from 'api_xukaiyu/app/login';
import { received_record } from '../../api_xukaiyu/app/share_redpacket';
import { registerOrlogin, sendMobileCode, loginByToken } from "api_xukaiyu/app/login";

const queryObject = util.parseQueryString();
let cardInfo = {
    '0': {
        "unit": '元',
        "limit": '无门槛红包'
    },
    '1': {
        "unit": '折',
        "limit": '折扣红包'
    },
    "2": {
        "unit": '嘿豆',
        "limit": '嘿豆抵现'
    }
};
class GetCoupon extends React.Component {
    constructor() {
        super();
        this.state = {
            formData: {
                mobile: "",
                mobileCode: "",
                appType: "H5",
                token: ""
            },
            receivedRecord: [],//手气列表
            hasGet: false,//是否领取过
            isLogin: false,//是否登陆
            userPhone: '',//用户注册后手机号
            redPacket: null,//领取奖励
            errInfo: '',//为什么无奖励

        };
    }

    // 0-抵扣红包 1-折扣红包 2-嘿豆
    componentDidMount() {
        let redPacketNo = this.props.match.params.redPacketNo;
        const queryObject = util.parseQueryString();
        let wechatTokenFromUrl = queryObject.token;
        let wechatTokenFromLocal = localStorage.getItem("wechatToken");
        const token = wechatTokenFromUrl || wechatTokenFromLocal; // 优先使用url的token
        loginStatus().then(data => {
            this.setState({
                userPhone: data.data.mobile,
                isLogin: true
            }, () => {
                receive_red_packet({ redPacketNo, token }).then(data => {
                    this.setState({
                        redPacket: data.data
                    }, () => {
                        this.receivedRecord();
                    })
                }).catch((err) => {
                    if (err.code == '2' || err.code == '5') {
                        this.setState({
                            errInfo: err.message
                        })
                        return false;
                    }
                })


            })
        }, () => {
            this.setState({
                isLogin: false
            })
            return false;
        })
        this.receivedRecord();

        //设置分享
        // let shareData = {};
        // shareData.link =`https://heyjie.wdai.com/m/app/fightRedEnvelope.html?from=singlemessage#/GetCoupon/${redPacketNo}`;
        // shareData.title = `吃喝玩乐5折起，新人仅需1分钱！还送大红包！`;
        // shareData.desc = `我80%的好友都注册了，你还等什么呢`;
        // wxShare(shareData);
    }
    //红包列表
    receivedRecord() {
        let redPacketNo = this.props.match.params.redPacketNo;
        received_record({ redPacketNo }).then(data => {
            this.setState({
                receivedRecord: data.data
            })
        })
    }

    render() {
        let { receivedRecord, userPhone, redPacket, isLogin, errInfo, formData } = this.state;
        return (<div className={style.GetCoupon}>
            <div className={style.header}></div>
            {
                isLogin ? <div className={style.getTicket}>
                    {redPacket ? <div>
                        <div className={style.hasTicket}>
                            <div className={style.title}></div>
                            <div className={style.content} onClick={() => {
                                util.checkWechatEnv((res) => {
                                    if (res == 'miniprogram') {
                                        wx.miniProgram.switchTab({
                                            url: '/pages/index/index'
                                        })
                                    } else {
                                        location.href = "./index.html"
                                    }
                                })

                            }}>
                                <div className={style.name}>拼手气红包</div>
                                <div className={style.time}>{redPacket.startTime}至{redPacket.endTime}可用</div>
                                <div className={style.money}>
                                    <div className={style.num}>{util.Mul(parseFloat(redPacket.denomination), redPacket.prizeType == 1 ? 10 : 1)}<span>{cardInfo[redPacket.prizeType].unit}</span></div>
                                    <div className={style.limit}>{cardInfo[redPacket.prizeType].limit}</div>
                                </div>
                            </div>
                        </div>
                    </div> :
                        <div className={style.noticket}>
                            <div className={style.tips}>{errInfo}</div>
                            <div className={style.getOhter} onClick={() => {
                                util.checkWechatEnv((res) => {
                                    if (res == 'miniprogram') {
                                        wx.miniProgram.switchTab({
                                            url: '/pages/category/category'
                                        })
                                    } else {
                                        location.href = './category.html';
                                    }
                                })
                            }}></div>
                        </div>}
                    <div className={style.phone}>优惠券将放入账户 {userPhone}<span onClick={() => {
                        logout().then(data => {
                            this.setState({
                                isLogin: false
                            }, () => {
                                location.reload();
                            })
                        })
                    }}>（更换手机号）</span></div>
                </div> : <div className={style.getModel}>
                        <div className={style.phoneInput}>
                            <input type="tel" onChange={(e) => {
                                this.inputOnChange("mobile", e.target.value)
                            }} value={formData.mobile} placeholder={'请输入你的手机号'} maxLength={11} />
                        </div>
                        <div className={style.codeInput}>
                            <input type="tel" onChange={(e) => {
                                this.inputOnChange("mobileCode", e.target.value)
                            }} value={formData.mobileCode} placeholder={'请输入验证码'} maxLength={6} />
                            <TimmerBtn className={style.sendBtn} disabled={!util.isMobile(formData.mobile)} disabledClick={() => {
                                if (!formData.mobile) {
                                    Toast.info("请先输入手机号");
                                    return;
                                }
                                if (!util.isMobile(formData.mobile)) {
                                    Toast.info("请输入正确的手机号")
                                }
                                return false;
                            }} validClick={(callback) => {
                                this.getMobileCode(callback || function () { });
                            }} />
                        </div>
                        <div className={style.getBtn} onClick={this.login}></div>
                        <div className={style.tips}>红包将会放入绑定手机号的出卡啦权益账户中</div>
                    </div>
            }

            {isLogin ? <div className={style.receivedRecord}>
                <div className={style.header}></div>
                <div className={style.List}>
                    {
                        receivedRecord.length ? receivedRecord.map((item, index) => {
                            return <div key={index} className={style.luckItem}>
                                <div className={style.luckImg}><img src={item.headImg || "//oss.unionvip.com/platformvip_20190916190844098.png"} alt="" /></div>
                                <div className={style.luckInfo}>
                                    <div className={style.name}>{item.nickName}</div>
                                    <div className={style.time}>{item.receiveTime}</div>
                                </div>
                                <div className={style.award}>
                                    <div className={style.awardInfo}>{item.prizeType == 2 ? parseInt(item.denomination || 0) : (util.Mul(parseFloat(item.denomination), item.prizeType == 1 ? 10 : 1))}{cardInfo[item.prizeType].unit}</div>
                                </div>
                            </div>
                        }) : <div className={style.nodata}>暂无数据</div>
                    }
                </div>
            </div> : ''}
            <div className={style.explain}>
                <div className={style.title}></div>
                <div className={style.content}>
                    1.用户购买卡券成功后即可分享红包给微信好友；<br />
                    2.每位用户每天至多可以领取3个红包；<br />
                    3.领取到的红包/嘿豆可进入公众号“出卡啦权益”--个人中心--红包 进行查看，逾期未用将会消失；<br />
                    4.红包/嘿豆可以在购买卡券商品支付时使用，每笔订单限使用1个红包，红包不找零；<br />
                    5.购买卡券的手机号需为领取红包时使用的手机号；<br />
                    6.出卡啦权益保留法律范围内允许的活动解释权；
                </div>
            </div>
        </div>
        );
    }

    // 输入监听
    inputOnChange(type, value) {
        const formData = { ...this.state.formData };
        formData[type] = value || "";
        this.setState({
            formData: formData
        })
    }

    // 微信中键盘退出页面无法回位问题修复
    inputOnBlurFix() {
        setTimeout(function () {
            var scrollHeight = document.documentElement.scrollTop || document.body.scrollTop || 0;
            window.scrollTo(0, Math.max(scrollHeight - 1, 0));
        }, 100);
    }
    // 获取手机验证码
    getMobileCode(callback) {
        sendMobileCode({
            mobile: this.state.formData.mobile,
            token: localStorage.getItem('wechatToken')
        }).then(() => {
            callback && callback();
        })
    }

    // 登录
    login = () => {
        // 验证数据
        if (!this.state.formData.mobile) {
            Toast.info("请输入手机号");
            return;
        }
        if (!util.isMobile(this.state.formData.mobile)) {
            Toast.info("请输入正确的手机号");
            return;
        }
        if (!this.state.formData.mobileCode) {
            Toast.info("请输入验证码");
            return;
        }

        // 登录请求
        registerOrlogin({ ...this.state.formData, ...{ token: queryObject.token || localStorage.getItem('wechatToken') } }).then((res) => {
            localStorage.setItem("heyjie-token", res.data.token);
            let href0=location.href.split('?')[0];
            let href1=location.href.split('?')[1];
            location.replace(location.href.includes('?')?(href0+`?t=${Date.now()}&${href1}`):(href0+`?t=${Date.now()}`))
        });
        return false;
    }


    // 微信中键盘退出页面无法回位问题修复
    inputOnBlurFix() {
        setTimeout(function () {
            var scrollHeight = document.documentElement.scrollTop || document.body.scrollTop || 0;
            window.scrollTo(0, Math.max(scrollHeight - 1, 0));
        }, 100);
    }
}

export default GetCoupon;